package com.mathmodeling.controller;

import com.mathmodeling.dto.ApiResponse;
import com.mathmodeling.dto.LoginRequest;
import com.mathmodeling.dto.LoginResponse;
import com.mathmodeling.entity.User;
import com.mathmodeling.repository.UserRepository;
import com.mathmodeling.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.UUID;

@RestController
@RequestMapping("/auth")
public class AuthController {
    
    @Autowired
    private AuthenticationManager authenticationManager;
    
    @Autowired
    private UserRepository userRepository;
    
    @Autowired
    private PasswordEncoder passwordEncoder;
    
    @Autowired
    private JwtUtil jwtUtil;
    
    @PostMapping("/login")
    public ApiResponse<LoginResponse> login(@Valid @RequestBody LoginRequest loginRequest) {
        try {
            System.out.println("🔍 开始登录验证，用户名: " + loginRequest.getUsername() + ", 角色: " + loginRequest.getRole());
            
            // 验证用户凭据
            Authentication authentication = authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(
                            loginRequest.getUsername(),
                            loginRequest.getPassword()
                    )
            );
            
            System.out.println("✅ Spring Security认证成功");
            SecurityContextHolder.getContext().setAuthentication(authentication);
            
            // 获取用户信息
            System.out.println("🔍 从数据库查找用户: " + loginRequest.getUsername());
            User user = userRepository.findByUsername(loginRequest.getUsername())
                    .orElseThrow(() -> new RuntimeException("用户不存在"));
            
            System.out.println("✅ 找到用户: " + user.getUsername() + ", ID: " + user.getId());
            
            // 验证请求的角色是否与用户实际角色匹配
            String actualRole = determineUserRole(user);
            String requestedRole = loginRequest.getRole();
            
            System.out.println("🎭 验证角色 - 请求角色: " + requestedRole + ", 实际角色: " + actualRole);
            
            if (!actualRole.equals(requestedRole)) {
                System.out.println("❌ 角色不匹配");
                return ApiResponse.error(401, "用户名或密码错误");
            }
            
            // 生成JWT令牌
            String token = jwtUtil.generateToken(loginRequest.getUsername(), actualRole);
            System.out.println("🔑 生成JWT令牌成功");
            
            LoginResponse loginResponse = new LoginResponse(token, user.getId(), actualRole, user.getTeamId());
            
            System.out.println("🎉 登录成功，返回响应");
            return ApiResponse.success("登录成功", loginResponse);
            
        } catch (Exception e) {
            System.out.println("❌ 登录失败，异常: " + e.getMessage());
            e.printStackTrace();
            return ApiResponse.error(401, "用户名或密码错误");
        }
    }
    
    // 根据用户信息判断实际角色
    private String determineUserRole(User user) {
        System.out.println("🔍 determineUserRole被调用，用户名: '" + user.getUsername() + "'");
        
        // 优先使用数据库中存储的角色
        if (user.getRole() != null && !user.getRole().trim().isEmpty()) {
            System.out.println("✅ 使用数据库中存储的角色: " + user.getRole());
            return user.getRole();
        }
        
        // 如果数据库中没有角色信息，则通过用户名前缀判断
        if (user.getUsername() == null || user.getUsername().trim().isEmpty()) {
            System.out.println("❌ 用户名为空，返回默认角色student");
            return "student";
        }
        
        if (user.getUsername().startsWith("admin")) {
            System.out.println("✅ 通过用户名前缀判断为admin角色");
            return "admin";
        } else if (user.getUsername().startsWith("teacher")) {
            System.out.println("✅ 通过用户名前缀判断为teacher角色");
            return "teacher";
        } else {
            System.out.println("✅ 通过用户名前缀判断为student角色");
            return "student";
        }
    }
    
    @PostMapping("/register")
    public ApiResponse<String> register(@Valid @RequestBody LoginRequest registerRequest) {
        try {
            // 检查用户名是否已存在
            if (userRepository.existsByUsername(registerRequest.getUsername())) {
                return ApiResponse.error(400, "用户名已存在");
            }
            
            // 创建新用户
            User user = new User();
            user.setId(UUID.randomUUID().toString());
            user.setUsername(registerRequest.getUsername());
            user.setPassword(passwordEncoder.encode(registerRequest.getPassword()));
            
            userRepository.save(user);
            
            return ApiResponse.success("注册成功");
            
        } catch (Exception e) {
            return ApiResponse.error(500, "注册失败: " + e.getMessage());
        }
    }
} 